package com.csp.main.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csp.common.utils.R;
import com.csp.main.entity.UserAdmin;
import com.csp.main.entity.UserCommon;
import com.csp.main.entity.vo.AdminLogin;
import com.csp.main.service.UserAdminService;
import com.csp.main.service.UserCommonService;
import com.csp.main.utils.JWTUtils;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 * 管理员 前端控制器
 * </p>
 *
 * @author csp
 * @since 2022-06-05
 */
@RestController
@RequestMapping("/user_admin")
@CrossOrigin
public class UserAdminController {

    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private UserCommonService userCommonService;


    @GetMapping("/user_admin_list")
    public R getUserAdminList(){
        List<UserAdmin> userAdminList = userAdminService.list(null);
        return R.ok().data("userAdminList",userAdminList);
    }

    @PostMapping("/user_admin_add")
    public R addUserAdmin(@RequestBody UserAdmin userAdmin){
        boolean save = userAdminService.save(userAdmin);
        return save?R.ok():R.error();
    }

    @PostMapping("/user_admin_login")
    public R login(@RequestBody AdminLogin adminLogin, HttpServletResponse response){
        String name = adminLogin.getName();
        String password = adminLogin.getPassword();
        if(StringUtils.isNoneEmpty(name)&&StringUtils.isNotEmpty(password)){
            QueryWrapper<UserAdmin> wrapper = new QueryWrapper<>();
            wrapper.eq("name",name);
            wrapper.eq("password",password);
            List<UserAdmin> userAdminList = userAdminService.list(wrapper);
            if(userAdminList.size()!=0){
                String id = userAdminList.get(0).getId();
                String token = JWTUtils.createToken(id);
                response.setHeader(JWTUtils.USER_LOGIN_TOKEN,token);
                return R.ok().data("token",token);
            } else {
                return R.error();
            }
        }else {
            return R.error();
        }
    }

    @GetMapping("/user_list")
    public R getUserList(){
        List<UserCommon> userCommonList = userCommonService.list(null);
        return R.ok().data("userAdminList",userCommonList);
    }
}

